package com.sihai.ehr.web.action.transaction;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.*;
import com.sihai.ehr.model.sys.AuditStatus;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.TransactionService;
import com.sihai.ehr.utils.DateUtil;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.SearchFormPojo;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.Iterator;
import java.util.List;

/**
 * author: wxn
 * since: 13-4-8 下午9:38
 * 员工异动action
 */
@Results({
        @Result(name = "main", location = "transaction_main.jsp"),
        @Result(name = "list", location = "transaction_list.jsp"),
        @Result(name = "add", location = "transaction_input.jsp"),
        @Result(name = "audit", location = "transaction_audit.jsp")
})
public class TransactionAction extends EHRAction {
    @BeanInject
    private TransactionService transactionService;
    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private EmployeeService employeeService;

    private LimitedList<Transaction> transactions;
    private Transaction transaction;
    private Transaction.TransactionType type;

    private List<Organization> organizations;

    private String deleteMessage;

    private boolean showDateInputSearch = true;
    protected SearchFormPojo searchFormPojo;

    @Action("/transaction/organization_main")
    @Override
    public String execute() throws Exception {
        listAction = "/transaction/list-organization.xhtml";
        listTitle = "部门异动";
        main();
        return "main";
    }
    @Action("/transaction/promotion_main")
    public String mainPromotion() throws Exception {
        listAction = "/transaction/list-promotion.xhtml";
        listTitle = "普升异动";
        main();
        return "main";
    }
    @Action("/transaction/demotion_main")
    public String mainDemotion() throws Exception {
        listAction = "/transaction/list-demotion.xhtml";
        listTitle = "降职异动";
        main();
        return "main";
    }
    private void main() throws Exception {
        showChildOrg = true;
        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
    }

    @Action("/transaction/list-organization")
    public String listForOrganization()throws Exception{
        type = Transaction.TransactionType.organization;
        list(Transaction.TransactionType.organization);
        this.setPageUrl("transaction/list-organization.xhtml");
        return "list";
    }

    //升职
    @Action("/transaction/list-promotion")
    public String listForPromotion()throws Exception{
        type = Transaction.TransactionType.promotion;
        list(Transaction.TransactionType.promotion);
        this.setPageUrl("transaction/list-promotion.xhtml");
        return "list";
    }

    //降职
    @Action("/transaction/list-demotion")
    public String listForDemotion()throws Exception{
        type = Transaction.TransactionType.demotion;
        list(Transaction.TransactionType.demotion);
        this.setPageUrl("transaction/list-demotion.xhtml");
        return "list";
    }

    private void list(Transaction.TransactionType type)throws Exception{
        transactions = transactionService.findTransactionByOrganizationAndType(organizationId, type, searchFormPojo, createLimit(), createSorter());
        this.paging(transactions);
    }

    //--------细分，便于权限
    //跳转到部门异动添加界面
    @Action("/transaction/add-organization")
    public String addOrganization()throws Exception{
        return toEdit();
    }
    //跳转到部门异动修改界面
    @Action("/transaction/edit-organization")
    public String editOrganization()throws Exception{
        return toEdit();
    }
    //跳转到晋升异动添加界面
    @Action("/transaction/add-promotion")
    public String addPromotion()throws Exception{
        return toEdit();
    }
    //跳转到晋升异动修改界面
    @Action("/transaction/edit-promotion")
    public String editPromotion()throws Exception{
        return toEdit();
    }
    //跳转到降职异动添加界面
    @Action("/transaction/add-demotion")
    public String addDemotion()throws Exception{
        return toEdit();
    }
    //跳转到降职异动修改界面
    @Action("/transaction/edit-demotion")
    public String editDemotion()throws Exception{
        return toEdit();
    }

    private String toEdit()throws Exception{
        if(transaction != null && transaction.getId() != null && transaction.getId() > 0){
            transaction = transactionService.get(transaction.getId());
        }
        return "add";
    }

    @Action("/transaction/save")
    public String save()throws Exception{
        if(transaction != null){
            EmployeeinfoWork work = employeeService.getEmployeeinfoWork(transaction.getWork().getId());
            transaction.setOldOrganization(work.getOrganization());
            transaction.setOldDuty(work.getDuty());
            transaction.setOldGradeLevel(work.getGradeLevel());
            if(type != Transaction.TransactionType.organization){
                transaction.setNewOrganization(work.getOrganization());
            }
            transaction.setMoveDateTiem(DateUtil.createDate(getParameter("t_date"), "yyyy-MM-dd"));
            transaction.setType(type);
            transaction.setStatus(AuditStatus.wait_audit);
            Organization organization = organizationService.get(organizationId);
            transaction.setTopOrganization(organization);

            if(transaction.getId() != null && transaction.getId() > 0){//update
                Transaction t = transactionService.get(transaction.getId());
                t.setNewOrganization(transaction.getNewOrganization());
                t.setNewDuty(transaction.getNewDuty());
                t.setNewGradeLevel(transaction.getNewGradeLevel());
                transactionService.save(t);
            }else{//create
                transactionService.save(transaction);
            }
        }
        if(type == Transaction.TransactionType.organization){
            return execute();
        }else if(type == Transaction.TransactionType.promotion){
            return mainPromotion();
        }else{
            return mainDemotion();
        }
    }

    //删除部门异动
    @Action("/transaction/delete-organization")
    public String deleteOrganization()throws Exception{
        doDelete();
        return execute();
    }

    //删除升职异动
    @Action("/transaction/delete-promotion")
    public String deletePromotion()throws Exception{
        doDelete();
        return mainPromotion();
    }

    //删除降职异动
    @Action("/transaction/delete-demotion")
    public String deleteDemotion()throws Exception{
        doDelete();
        return mainDemotion();
    }
    private void doDelete()throws Exception{
        String ids = getParameter("transaction_ids");
        if(StringUtils.isBlank(ids)){
            return;
        }
        try {
            transactionService.delete(ids);
        } catch (Exception e) {
            deleteMessage = "delete-error";
        }
    }


    //审核部门异动
    @Action("/transaction/audit-organization")
    public String auditOrganization()throws Exception{
        type = Transaction.TransactionType.organization;
        return toAudit();
    }

    //审核升职异动
    @Action("/transaction/audit-promotion")
    public String auditPromotion()throws Exception{
        type = Transaction.TransactionType.promotion;
        return toAudit();
    }

    //审核降职异动
    @Action("/transaction/audit-demotion")
    public String auditDemotion()throws Exception{
        type = Transaction.TransactionType.demotion;
        return toAudit();
    }

    private List<EmployeeinfoEducation> educations; //员工教育列表
    private List<EmployeeinfoTrain> trains; //员工培训列表
    private List<EmployeeWorkExperience> workExperiences; //员工工作经历列表
    private List<EmployeeinfoFamily> families; //员工家庭关系列表

    private List<List<TransactionAuditing>> audits;
    //跳转到审核页面
    private String toAudit()throws Exception{
        if(transaction != null && transaction.getId() != null){
            transaction = transactionService.get(transaction.getId());
            EmployeeinfoBase base = transaction.getWork().getBaseId();
            educations = employeeService.getEducationList(base, null, null);
            trains = employeeService.getTrainList(base, null, null);
            workExperiences = employeeService.getWorkExperienceList(base, null, null);
            families = employeeService.getEmployeeFamilyList(base, null, null);

            //得到当前审核历史记录(没有就先保存一个审核流程次数)
            audits = transactionService.findTransactionAuditing(transaction.getId());
            if(audits == null || audits.isEmpty()){
                transactionService.saveTransactionAuditingProcess(transaction.getId());
                audits = transactionService.findTransactionAuditing(transaction.getId());
            }
            //检查当前登录用户是否可以审核当前结点
            if(transaction.getWork() != null && audits != null && !audits.isEmpty()){
                checkCanAudit(transaction.getWork().getDuty(), audits.get(audits.size()-1));
            }
            currentAuditType = (type == Transaction.TransactionType.organization ? AuditType.audit_transaction_organization.toString() : AuditType.audit_transaction_other.toString());

        }else{
            if(type == Transaction.TransactionType.organization){
                return execute();
            }else if(type == Transaction.TransactionType.promotion){
                return mainPromotion();
            }else{
                return mainDemotion();
            }
        }
        return "audit";
    }


    public LimitedList<Transaction> getTransactions() {
        return transactions;
    }

    public Transaction getTransaction() {
        return transaction;
    }

    public void setTransaction(Transaction transaction) {
        this.transaction = transaction;
    }

    public Transaction.TransactionType getType() {
        return type;
    }

    public void setType(Transaction.TransactionType type) {
        this.type = type;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public List<EmployeeinfoEducation> getEducations() {
        return educations;
    }

    public List<EmployeeinfoTrain> getTrains() {
        return trains;
    }

    public List<EmployeeWorkExperience> getWorkExperiences() {
        return workExperiences;
    }

    public List<EmployeeinfoFamily> getFamilies() {
        return families;
    }

    public List<List<TransactionAuditing>> getAudits() {
        return audits;
    }

    public String getDeleteMessage() {
        return deleteMessage;
    }

    public boolean isShowDateInputSearch() {
        return showDateInputSearch;
    }

    public SearchFormPojo getSearchFormPojo() {
        return searchFormPojo;
    }

    public void setSearchFormPojo(SearchFormPojo searchFormPojo) {
        this.searchFormPojo = searchFormPojo;
    }
}
